package com.prim.threadpool;

import java.util.Arrays;
import java.util.concurrent.*;
import java.util.concurrent.locks.LockSupport;

/**
 * @author prim
 * 测试线程池停止
 */
public class DemoStopThreadPool {
    static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
            5,
            10,
            5,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(),
            new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    System.out.println("有任务被拒绝执行了");
                }
            }
    );

    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 9; i++) {
                    int n = i;
                    LockSupport.parkNanos(1000 * 1000 * 1000 * 1L);//挂起1s;
                    System.out.println("尝试提交一个任务:" + n);
                    poolExecutor.submit(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("任务开始执行:" + n);
                            try {
                                Thread.sleep(3000L);
                                System.out.println("任务执行结束:" + n);
                            } catch (InterruptedException e) {
                                System.out.println("异常：" + e.getMessage());
                            }
                        }
                    });
                }
            }
        }).start();
        Thread.sleep(5000L);
//        poolExecutor.shutdownNow();//shutdown
//        System.out.println(">>>>>> 执行了shutdown方法");
//        System.out.println("isShutdown:" + poolExecutor.isShutdown());
        poolExecutor.shutdown();
        System.out.println("准备执行awaitTermination");
        while (!poolExecutor.awaitTermination(1, TimeUnit.SECONDS)) {
            System.out.println("检测线程池未关闭");
        }
        System.out.println("线程池已关闭");
    }
}
